package servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

/*
        //解决POST提交时的中文乱码问题，无法解决GET提交乱码问题
        //setCharacterEncoding()方法设置了请求正文中的字符编码
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String age = req.getParameter("age");

        System.out.println("name = "+name);
        System.out.println("age = "+age);*/



        // 这里接收到的name，其字符编码为ISO8859-1
        String name = req.getParameter("name");
/*
        // 对于请求中的中文乱码的万能解决方案

        // 打散：将name字符串按照原编码进行打散
        byte[] bytes = name.getBytes("ISO8859-1");
        // 组装：将bytes字节数组按照指定字符编码进行组装，组装为String
        name = new String(bytes, "UTF-8");*/

        String age = req.getParameter("age");

        System.out.println("name = " + name);
        System.out.println("age = " + age);



        //设置响应的MIME类型(video/mp4, image/jpg)
        //其中可以指定MIME的字符编码，即响应体的字符编码
        resp.setContentType("text/html;charset=UTF-8");

        //setCharacterEncoding()方法的使用前提是，之前必须要先使用setContentType
        //setCharacterEncoding()方法用于修改ContentType的MIME类型字符编码
//        resp.setCharacterEncoding("UTF-8");

        //获取标准输出流
        PrintWriter writer = resp.getWriter();

        //向标准输出流中写入数据，那么客户端浏览器就会直接看到这些数据
        writer.append("abc");
        writer.append("def");
        writer.print(name);
        writer.write("name");

        //关闭
        writer.close();


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
